// pages/lawhall/index.js
const app = getApp()
const {
  messageset,
  messagetop,
  pay,
  messagerecruit,
  messagefabu,
  messageedit,
  editrecruit
} = require('../../utils/api')
const {
  formatDate
} = require('../../utils/util')
const dateTimePicker = require('../../utils/dateTimePicker.js');
const {
  fetch,
  newFetch,
  hasSensitiveWords,
  replaceAll
} = require('../../utils/fetch')
const {
  BASEURL
} = require('../../utils/baseurl')
import {
  Base
} from '../../utils/base.js';
var base = new Base();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: '',
    type_id: 0,
    sub_type_id: 0,
    sub_type_info: [],

    title: '',
    details: '', //描述
    address: '',

    pushName: '',
    pushPhone: '',

    logo_img: [],
    imgs: [],

    sel_start_time: '',
    sel_top_idx: -1,
    topInfo: [],
    cur_mid: 0,

    remark_arr: [],
    region: ['请选择地区', '', ''],
    workyear_idx: 0,
    yuexin_idx: 0,
    xueli_idx: 0,
    xueli_data: [{
        id: 0,
        name: '请选择学历'
      },
      {
        id: 1,
        name: '初中及以下'
      },
      {
        id: 2,
        name: '高中'
      },
      {
        id: 3,
        name: '技校'
      },
      {
        id: 4,
        name: '中专'
      },
      {
        id: 5,
        name: '大专'
      },
      {
        id: 6,
        name: '本科'
      },
      {
        id: 7,
        name: '研究生'
      },
      {
        id: 8,
        name: '硕士'
      },
      {
        id: 9,
        name: '博士'
      }
    ],
    workyear_data: [{
        id: 0,
        name: '不限'
      },
      {
        id: 1,
        name: '1年以内'
      },
      {
        id: 2,
        name: '1-2年'
      },
      {
        id: 3,
        name: '3-5年'
      },
      {
        id: 4,
        name: '6-7年'
      },
      {
        id: 5,
        name: '8-10年'
      },
      {
        id: 6,
        name: '10年以上'
      }
    ],
    yuexin_data: [{
        id: 0,
        name: '面议'
      },
      {
        id: 1,
        name: '1000元以下'
      },
      {
        id: 2,
        name: '1001-2000元'
      },
      {
        id: 3,
        name: '2001-3000元'
      },
      {
        id: 4,
        name: '3001-5000元'
      },
      {
        id: 5,
        name: '5001-8000元'
      },
      {
        id: 6,
        name: '8001-12000元'
      },
      {
        id: 7,
        name: '12001-20000元'
      },
      {
        id: 8,
        name: '20000以上'
      }
    ],
    remark_data_chuzhu: [{
        id: 1,
        sel: 0,
        name: '交通便利'
      },
      {
        id: 2,
        sel: 0,
        name: '中介勿扰'
      },
      {
        id: 3,
        sel: 0,
        name: '精装修'
      },
      {
        id: 4,
        sel: 0,
        name: '随时看房'
      }
    ],
    remark_data_car: [{
        id: 1,
        sel: 0,
        name: '短租'
      },
      {
        id: 2,
        sel: 0,
        name: '长租'
      },
      {
        id: 3,
        sel: 0,
        name: '旅游'
      },
      {
        id: 4,
        sel: 0,
        name: '班车'
      }
    ],
    valtitle: '',

    iscover: true,
    tip: 'init',
    show_tip: 0,
    imageList: [],
    imagselogs: [],
    uploadList: [],
    uploadimgs: [],
    customItem: '全部',


    checked: false,
    checked1: true,
    startimedate: formatDate(new Date()),
    freindex: 0,
    topInfo: Array,
    timeArr: ['七天', '半个月', '一个月', '一季度', '半年', '一年'],
    currentDate: new Date().getTime(),
    show: false,
    // type_id:0,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      }
      return value
    },

    // orderData:"选择时间",

    dateTime1: null,
    dateTimeArray1: null,
    startYear: 2000,
    endYear: 2050,

    editval: {}, //编辑
    editid: 0, //编辑id
    ispageEdit: true,
    typeindex: null,
    picker_time: '00:00',

    formId: '',
    specificarea: null,
    systemInfo: '',
    isShare: false,
    isagent: 0,
    pubdisabled: false,
    savedisabled: false,
    savedorderCode: {},

    show_tip: 0,
    tip: 'init',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if (wx.getStorageSync('specificarea')) {
      this.setData({
        specificarea: wx.getStorageSync('specificarea')
      })
    }

    if (wx.getStorageSync('userInfo')) {
      let userInfo = wx.getStorageSync('userInfo');
      if (userInfo.isagent == null) {
        this.setData({
          isagent: 0
        })
      } else {
        this.setData({
          isagent: userInfo.isagent
        })
      }

      if (this.data.isagent == 0) {
        this.setData({
          pushPhone: userInfo.mobile,
          pushName: userInfo.nickname,
        })
      }
    }
    if (wx.getStorageSync('currentAddress')) {
      let addressval = wx.getStorageSync('currentAddress').address_component;
      let rgaddress = [addressval.city, addressval.province, addressval.district]
      this.setData({
        region: rgaddress
      })
    }

    fetch(`wx/message/${this.data.specificarea}/messageset`, 'POST').then(res => {
      this.setData({
        toptimes: res.toptimes
      })
    })

    fetch(`wx/message/${this.data.specificarea}/messagetop`, 'POST').then(res => {
      this.setData({
        topInfo: res
      })
    })

    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      dateTime1: obj1.dateTime,
      dateTimeArray1: obj1.dateTimeArray
    });
    if (options.index) {
      var type_info = app.globalData.addtype[options.index];
      this.setData({
        typeindex: options.index
      })
      if (type_info.typeimg) {
        // this.setData({
        //   imageList: [type_info.typeimg],
        //   imagselogs: [type_info.typeimg],
        // })
      }
      var type_child_info = type_info['childList'];
      var sub_type_id = 0;

      if (type_child_info.length > 0) {
        sub_type_id = type_child_info[0]['id'];
      }
      this.setData({
        type: type_info.text,
        type_id: type_info.id,
        sub_type_info: type_child_info,
        sub_type_id: sub_type_id,
      })
      if (type_child_info.length > 0) {
        if (type_child_info[0].typeimg) {
          this.setData({
            imageList: [type_child_info[0].typeimg],
            imagselogs: [type_child_info[0].typeimg],
          })
        }
      }
    }
    if (options.ediddata) {
      var editdetails
      var edittitle
      if (options.details) {
        editdetails = decodeURIComponent(options.details)
      }
      if (options.edittitle) {
        edittitle = decodeURIComponent(options.edittitle)
      }
      // console.log(options,getApp().globalData.ediddata)
      // console.log(options.ediddata,JSON.parse(options.ediddata))

      var details = editdetails && editdetails.split('&nbsp;').join('\n')
      var isedtitle = edittitle && edittitle.split('&nbsp;').join('\n')
      
      this.setData({
        // editval: options.ediddata && JSON.parse(options.ediddata),
        editval: getApp().globalData.ediddata,
        ispageEdit: false,
      })
      let {
        editval
      } = this.data;

      var imgsdata = editval.imgs && editval.imgs.split(",");
      var editcity = editval.city && editval.city.split(",");
      var content = editval.content

      var content = editval.content && JSON.parse(editval.content);
      var staradtime = editval.startTime && editval.startTime.substr(editval.startTime.length - 6)
      if (content) {
        //  工作年限
        this.data.workyear_data.map((val, id) => {
          if (val.name == content.workyear) {
            this.setData({
              workyear_idx: id,
            })
          }
        })
        // 月薪
        this.data.yuexin_data.map((val, id) => {
          if (val.name == content.yuexin) {
            this.setData({
              yuexin_idx: id,
            })
          }
        })
        // 学历
        this.data.xueli_data.map((val, id) => {
          if (val.name == content.xueli) {
            this.setData({
              xueli_idx: id,
            })
          }
        })

      }

      // 第三层判断
      if (editval.typetwo && editval.typetwo) {
        this.setData({
          sub_type_id: editval.typetwo.id,
          sub_type_info: [editval.typetwo],
        })
      }
      editval.typeone.id==3?this.setData({checked:true}):this.setData({checked:false});
      this.setData({
        type: editval.typeone.title,
        type_id: editval.typeone.id,

        imageList: [editval.logo],
        imagselogs: [editval.logo],
        uploadList: imgsdata || [],
        uploadimgs: imgsdata || [],
        remark: editval.remark,

        title: isedtitle,
        details: details,
        pushName: editval.pushName,
        pushPhone: editval.pushPhone,
        address: editval.address,
        region: editcity,

        picker_time: staradtime || '00:00'
        // startimedate: editval.startTime || this.data.startimedate,
        // freindex: editval.day == 0 ? 0 : editval.day - 1

      })
    }
    if (options.editid) {
      this.setData({
        editid: options.editid
      })
    }

    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.system.indexOf('iOS') == 0) {
          that.setData({
            systemInfo: 'iOS'
          })
        } else {
          that.setData({
            systemInfo: 'Android'
          })
        }
      }
    })
  },
  bind_sub_type: function (e) {
    var id = e.currentTarget.dataset.id;
    var typeimg = e.currentTarget.dataset.typeimg;
    // base.getDataSet(e,'id')
    this.setData({
      sub_type_id: id,
      imageList: [typeimg],
      imagselogs: [typeimg],
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  // 输入框的值
  goinputtitle: function (e) {
    this.setData({
      title: e.detail.value
    })
  },
  // 输入框的描述值
  goinputdetail: function (e) {
    this.setData({
      details: e.detail.value
    })
  },
  // 输入框的联系人值
  goinputpushName: function (e) {
    this.setData({
      pushName: e.detail.value
    })
  },
  // 输入框的电话值
  goinputpushPhone: function (e) {
    this.setData({
      pushPhone: e.detail.value
    })
  },
  // 输入框地址
  goinputaddress: function (e) {
    this.setData({
      address: e.detail.value
    })
  },

  // 工作年限
  bindworkChange: function (e) {
    this.setData({
      workyear_idx: e.detail.value
    })
  },
  // 月薪
  bindyuexinChange: function (e) {
    this.setData({
      yuexin_idx: e.detail.value
    })
  },
  // 学历
  bindxueliChange: function (e) {
    this.setData({
      xueli_idx: e.detail.value
    })
  },

  // 地址选择
  bindRegionChange: function (e) {
    var val_arr = e.detail.value;
    if (val_arr[0] == '全部' && val_arr[1] == '全部' && val_arr[2] == '全部') {
      this.setData({
        region: ['请选择地区']
      })
      return;
    }
    this.setData({
      region: e.detail.value
    })
  },

  // 置顶时间
  bindTimeChange: function (e) {
    this.setData({
      picker_time: e.detail.value
    })
  },


  // 上传logo图片
  upload() {
    const _this = this
    let {
      imageList
    } = this.data
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths;
        for (var i = 0; i < tempFilePaths.length; i++) {
          imageList.push(tempFilePaths[i]);
          this.setData({
            imageList: imageList,
            iscover: false,
          })
          _this.setData({
            tip: '已选图片,正在上传..',
            show_tip: 1,
          })
          wx.uploadFile({
            url: `${BASEURL}wx/upload/image`,
            filePath: res.tempFilePaths[i],
            name: 'image',
            formData: {},
            success: (res) => {
              if (res.statusCode == 200) {
                var resdata = JSON.parse(res.data);
                let access_token = wx.getStorageSync('access_token');
                if (access_token) {
                  let url = 'https://api.weixin.qq.com/wxa/img_sec_check?access_token=' + access_token;
                  wx.request({
                    url: url,
                    method: 'POST',
                    header: {
                      'Content-Type': 'application/octet-stream'
                    },
                    data: {
                      media: resdata.data.url
                    },
                    success: function (res) {
                      // {"errcode":0,"errmsg":"ok"}
                    }
                  })
                }

                _this.setData({
                  // imagselogs:_this.data.imagselogs.concat(resdata.data.url),
                  imagselogs: [resdata.data.url],
                })

                _this.setData({
                  tip: '显示',
                  show_tip: 0
                })
              }

            },
            fail: function (res) {}
          })
        }
      }
    })
  },
  previewImage(e) {
    let index = e.target.dataset.index
    let {
      imageList
    } = this.data
    wx.previewImage({
      current: imageList[index],
      urls: imageList
    })
  },
  remove(e) {
    const _this = this
    let index = e.target.dataset.index
    let {
      imageList,
      imagselogs
    } = this.data
    wx.showModal({
      title: '提示',
      content: '您确定要删除本张图片吗？',
      success(res) {
        if (res.confirm) {
          imageList.splice(index, 1)
          imagselogs.splice(index, 1)
          _this.setData({
            imageList,
            imagselogs,
            iscover: true
          })
        } else if (res.cancel) {}
      }
    })
  },


  // 上传图片  九图
  uploadimg() {
    const _this = this
    let {
      uploadList,
      uploadimgs
    } = this.data
    var resupimg = []
    let arr = [];

    wx.chooseImage({
      count: 9 - uploadimgs.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        res.tempFilePaths.forEach((item, index) => {
          wx.uploadFile({
            url: `${BASEURL}wx/upload/image`,
            filePath: item,
            name: 'image',
            formData: {
              type: 'img'
            },
            success: (res) => {
              var resdata = JSON.parse(res.data);
              if (resdata.code == '200') {
                // arr.push({
                //   index: index,
                //   src: resdata.data.url
                // })
                resupimg[index] = resdata.data.url
                this.setData({
                  uploadimgs: resupimg
                })
                _this.setData({
                  tip: '显示',
                  show_tip: 0
                })
              } else if (resdata.code == '404') {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            },
            fail: function (res) {
              console.log(res, 'fail')
            }
          })
        })
        // var tempFilePaths = res.tempFilePaths;
        // for (var i = 0; i < tempFilePaths.length; i++) {
        //   // uploadList.push(tempFilePaths[i]);
        //   // _this.setData({
        //   //   uploadList: uploadList
        //   // })
        //   // resupimg.push(res.tempFilePaths[i])

        //   wx.uploadFile({
        //     url: `${BASEURL}wx/upload/image`,
        //     filePath: res.tempFilePaths[i],
        //     name: 'image',
        //     formData: {
        //       // file: uploadList,
        //       type: 'img'
        //     },
        //     success: (res) => {
        //       var resdata = JSON.parse(res.data);
        //       if (resdata.code == '200') {
        //         // resupimg.push(resdata.data)
        //         resupimg[i] = resdata.data.url
        //         this.setData({
        //           uploadimgs: resupimg
        //         })
        //         _this.setData({
        //               tip: '显示',
        //               show_tip: 0
        //             })
        //       } else if (resdata.code == '404') {
        //         wx.showToast({
        //           title: res.data.msg,
        //           icon: 'none'
        //         })
        //       }
        //     },
        //     fail: function (res) {
        //     }
        //   })
        // }
      }
    })
  },
  previewImagetwo(e) {
    let index = e.target.dataset.index
    let {
      uploadList
    } = this.data
    wx.previewImage({
      current: uploadList[index],
      urls: uploadList
    })
  },
  removeimg(e) {
    const _this = this
    let index = e.target.dataset.index
    let {
      uploadList,
      uploadimgs
    } = this.data

    this.data.uploadimgs.map((val, uploindex) => {
      if (uploindex == index) {
        wx.showModal({
          title: '提示',
          content: '您确定要删除本张图片吗？',
          success(res) {
            if (res.confirm) {
              // uploadList.splice(index, 1)
              uploadimgs.splice(index, 1)
              _this.setData({
                // uploadList,
                uploadimgs
              })
            } else if (res.cancel) {}
          }
        })
      }
    })
  },

  showToast: function (title) {
    wx.showToast({
      title,
      icon: 'none',
      duration: 1000
    })
  },

  // 置顶
  publishFN: function (e) {
    this.setData({
      formId: e.detail.formId
    })
    if (this.data.checked && !this.data.checked1) {
      wx.showToast({
        title: '请先同意入驻协议',
        icon: 'none',
        duration: 2000
      })
      return false
    }

    if (this.data.checked == false) {
      this.data.sel_top_idx = -1;
    } else {
      this.data.sel_top_idx = 0;
    }
    let data = this.data
    // console.log(this.data)
    if (!this.data.title) {
      this.showToast('请填写正确的标题');
      return;
    }
    if (this.data.imageList.length===0) {
      this.showToast('请上传封面展示图');
      return;
    }
    // debugger

    var newtitle = hasSensitiveWords(this.data.title);
    if (newtitle) {
      wx.showToast({
        title: '标题包含敏感词，已经自动处理为*，请重新编辑',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        title: replaceAll(this.data.title, newtitle),
      });
      return;
    }

    if (this.data.title.indexOf('*') == 0) {
      this.showToast('请填写正确的标题');
      return;
    }

    var newdetails = hasSensitiveWords(this.data.details)
    if (newdetails) {
      wx.showToast({
        title: '内容描述包含敏感词，已经自动处理为*，请重新编辑',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        details: replaceAll(this.data.details, newdetails),
      });
      return;
    }

    if (this.data.details && this.data.details.indexOf('*') == 0) {
      this.showToast('请填写正确的内容描述');
      return;
    }

    let userInfo = wx.getStorageSync('userInfo');
    if (this.data.isagent == 1) {
      this.setData({
        region: ''
      })
    }
    // debugger
    wx.showLoading({
      title: '发布中',
    })
    this.setData({
      pubdisabled: true
    })

    var re_param = {
      "area": this.data.specificarea,
      "memberId": userInfo["id"],
      "messageType1": data.type_id,
      "messageType2": data.sub_type_id,
      "logo": data.imagselogs,
      "imgs": data.uploadimgs,
      "remark": data.remark_arr.join(","),

      "title": data.title,
      "details": data.details && data.details.split('\n').join('&nbsp;'),
      "pushName": data.pushName,
      "pushPhone": data.pushPhone,
      "address": data.address,
      "city": data.region,

      "workyear": data.workyear_data[data.workyear_idx].name,
      "yuexin": data.yuexin_data[data.yuexin_idx].name,
      "xueli": data.xueli_data[data.xueli_idx].name,

      "istop": 0,
      "startTime": '',
      "day": 0,
      "deadline": 0,
      "fee": 0
    };

    console.log("this.data",this.data)
    console.log("this.data.type_id",this.data.type_id)
    if (this.data.type_id == 3) {
      if (!(this.data.sel_top_idx >= 0)) {
        var sel_top_info = this.data.topInfo[this.data.freindex];
        re_param["istop"] = 1;
        re_param["startTime"] = this.data.startimedate;
        re_param["day"] = sel_top_info['day'];
        re_param["deadline"] = this.data.toptimes;
        re_param["fee"] = sel_top_info['curmoney'];
      }
    }

    //选择置顶
    console.log("this.data.sel_top_idx",this.data.sel_top_idx)
    if (this.data.sel_top_idx >= 0) {
      var sel_top_info = this.data.topInfo[this.data.freindex];
      re_param["istop"] = 1;
      re_param["startTime"] = this.data.startimedate;
      re_param["day"] = sel_top_info['day'];
      re_param["deadline"] = this.data.toptimes;
      re_param["fee"] = sel_top_info['curmoney'];
    }

    var jump_url = '/pages/showmsg/index'; //'/pages/indexDetails/index?id=';

    console.log("this.data.type_id",this.data.type_id)
    if (this.data.type_id == 13) {
      jump_url = '/pages/showmsg/index'; //'/pages/indexDetails/index?id=';
    }
    this.data.cbj_url = jump_url;
    var that = this;

    //  判断是否是编辑页面
    console.log("this.data.editval",this.data.editval)
    if (this.data.editval) {
      if (this.data.editid) {
        re_param["istop"] = 1;
        delete(re_param['remark'])
        this.setData({
          savedisabled: true
        })
        // debugger
        re_param['id'] = this.data.editid
        re_param['adStartTime'] = this.data.picker_time
       
        if (this.data.editval.typeone.title == '招聘求职' || (this.data.editval.typetwo && this.data.editval.typetwo.title == '求职')) {
          if (this.data.checked) {
            wx.hideLoading()
            if (that.data.systemInfo == 'iOS') {
              wx.showToast({
                title: 'iOS不支持虚拟支付',
                icon: 'none',
                duration: 1500
              })
              return;
            }
            that.payRenew(this.data.editid, re_param)
          }  else {
            newFetch(`wx/message/${this.data.specificarea}/zhaopin/edit`, 'POST', re_param).then(res=>{
              if(res) {
                  wx.hideLoading()
                  that.endjump();
              }
            })
          }
          return;
        }
        // 商业信息
        if(this.data.type_id == 3) {
          if (this.data.checked) {
            wx.hideLoading()
            if (that.data.systemInfo == 'iOS') {
              wx.showToast({
                title: 'iOS不支持虚拟支付',
                icon: 'none',
                duration: 1500
              })
              return;
            }
            that.payRenew(this.data.editid, re_param)
          }  else {
            that.data.checked?re_param.istop=1:re_param.istop=0;
            newFetch(`wx/message/${this.data.specificarea}/edit`, 'POST', re_param).then(res => {
              if (res) {
                wx.hideLoading()
                that.endjump();
              }
            })
          }
          return;
        }
        // 普通信息
        if (this.data.checked) {
          wx.hideLoading()
          if (that.data.systemInfo == 'iOS') {
            wx.showToast({
              title: 'iOS不支持虚拟支付',
              icon: 'none',
              duration: 1500
            })
            return;
          }
          that.payRenew(this.data.editid, re_param)
        }  else {
          newFetch(`wx/message/${this.data.specificarea}/edit`, 'POST', re_param).then(res => {
            if (res) {
              wx.hideLoading()
              that.endjump();
            }
          })
        }
      }
    }

    console.log("this.data.typeindex",this.data.typeindex)
    if (this.data.typeindex) {
      if (this.data.type_id == 8) {
        newFetch(`wx/message/${this.data.specificarea}/zhaopin/fabu`, 'POST', re_param).then(res => {
          if (res.data) {
            that.data.cur_mid = res.data.id;
            if (res.data.istop > 0) {
              wx.hideLoading()
              if (that.data.systemInfo == 'iOS') {
                wx.showToast({
                  title: 'iOS不支持虚拟支付',
                  icon: 'none',
                  duration: 1500
                })
                return;
              }
              that.pay(res.data.fee, res.data.id, res.data.orderId);
            }
            if (res.data.istop == 0) {
              wx.hideLoading()
              that.endjump();
            }
            if (res.data.limit == 0) {
              wx.hideLoading()
              this.setData({
                isShare: true
              })
            }
            if (res.data.limit == 1) {
              wx.hideLoading()
              wx.showToast({
                title: '您的免费发布次数已用完',
                icon: 'none',
                duration: 1500
              })
              return;
            }
          }
        })
      } else {
        newFetch(`wx/message/${this.data.specificarea}/fabu`, 'POST', re_param).then(res => {
          if (res.data) {
            that.data.cur_mid = res.data.id;
            if (res.data.fee > 0) {
              wx.hideLoading()
              if (that.data.systemInfo == 'iOS') {
                wx.showToast({
                  title: 'iOS不支持虚拟支付',
                  icon: 'none',
                  duration: 1500
                })
                return;
              }
              that.pay(res.data.fee, res.data.id, res.data.orderId);
            }
            if (res.data.fee == 0) {
              wx.hideLoading()
              that.endjump();
            }
            if (res.data.limit == 0) {
              wx.hideLoading()
              this.setData({
                isShare: true
              })
            }
            if (res.data.limit == 1) {
              wx.hideLoading()
              wx.showToast({
                title: '您的免费发布次数已用完',
                icon: 'none',
                duration: 1500
              })
              return;
            }
          }
        })
      }
    }

  },
  pay: function (fee, typeId, orderId) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let obg = {
      area: this.data.specificarea,
      openId: userInfo['openid'],
      memberId: userInfo['id'],
      // money: '0.01',
      money: this.data.topInfo[this.data.freindex]['curmoney'],
      orderdesc: '小微服务',
      orderId: orderId,
      type: 1,
      typeId: typeId,
      formId: that.data.formId
      // type就是那个消息1，商户2 广告3 typeid就是对应的id
    }
    fetch(`wx/pay/${this.data.specificarea}/pay`, 'POST', obg).then(info => {
      wx.requestPayment({
        timeStamp: info.timeStamp,
        nonceStr: info.nonceStr,
        package: `prepay_id=${info.prepayId}`,
        signType: 'MD5',
        paySign: info.paySign,
        success: function (res) {
          wx.showToast({
            title: '付款成功',
            icon: 'success',
            duration: 2000
          })
          that.endjump();
        },
        fail: function (res) {
          that.setData({
            pubdisabled: false
          })
          wx.showToast({
            title: '取消付款成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    })
  },
  endjump: function () {
    var that = this;
    // setTimeout(() => {
      wx.redirectTo({
        url: that.data.cbj_url + "?id=" + 'indexid',
      })
    // }, 3000)
  },


  payRenew: function (typeId, re_param) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let obg = {
      area: this.data.specificarea,
      openId: userInfo['openid'],
      memberId: userInfo['id'],
      // money: '0.01',
      money: this.data.topInfo[this.data.freindex]['curmoney'],
      orderdesc: '小微服务',
      // orderId: orderId,
      type: 1,
      typeId: typeId,
      formId: that.data.formId
      // type就是那个消息1，商户2 广告3 typeid就是对应的id
    }
    fetch(`wx/pay/${this.data.specificarea}/payRenew`, 'POST', obg).then(info => {
      wx.requestPayment({
        timeStamp: info.timeStamp,
        nonceStr: info.nonceStr,
        package: `prepay_id=${info.prepayId}`,
        signType: 'MD5',
        paySign: info.paySign,
        success: function (res) {
          wx.showToast({
            title: '付款成功',
            icon: 'success',
            duration: 2000
          })
          that.saveEdit(info, re_param)
        },
        fail: function (res) {
          that.setData({
            savedisabled: false
          })
          wx.showToast({
            title: '取消付款成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    })
  },

  saveEdit:function (info, re_param) {
    var that = this;
    if (info.orderCode) {
      newFetch(`wx/pay/${this.data.specificarea}/checkOrderPayStatus`, 'POST', {
        orderId: info.orderCode
      }).then(res => {
        if (res.data.payStatus == 1) {
          re_param['payStatus'] = res.data.payStatus
          re_param['orderCode'] = res.data.orderCode
          if(this.data.type_id==8) {
            newFetch(`wx/message/${this.data.specificarea}/zhaopin/edit`, 'POST', re_param).then(res=>{
              if(res) {
                  wx.hideLoading()
                  that.endjump();
              }
            })
            return;
          }
          newFetch(`wx/message/${this.data.specificarea}/edit`, 'POST', re_param).then(res => {
            if (res) {
              wx.hideLoading()
              that.endjump();
            }
          })
        }
      })
    }
  },

  compare: function (prop) {
    return function (a, b) {
      let v1 = a[prop];
      let v2 = b[prop];
      return v1 - v2; //从小到大
      // return v2 - v1; //从大到小
    };
  },

  // 是否置顶
  onChange(event) {
    if (this.data.type_id == 3 || this.data.type_id == '3') {
      if(!this.data.ispageEdit) {
        this.setData({
          checked: event.detail
        })
        return
      }

      wx.showToast({
        title: '商业信息发布必须置顶',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    this.setData({
      checked: event.detail
    })
  },
  onChange1(event) {
    this.setData({
      checked1: event.detail
    })
  },

  bindPickerChange: function (e) {
    this.setData({
      freindex: e.detail.value
    })
  },
  togglePicker() {
    this.setData({
      show: !this.data.show,
    })
  },

  jumpToAgreement() {
    wx.navigateTo({
      url: '/pages/login/agreement'
    })
  },

  changeDateTime1(e) {
    let month = e.detail.value[1] + 1;
    let dtime = e.detail.value[2] + 1;
    let atime = '20' + e.detail.value[0] + '-' + month + '-' + dtime + ' ' + e.detail.value[3] + ':' + e.detail.value[4];
    this.setData({
      startimedate: atime
    })
  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1,
      dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },

  shareClose() {
    this.setData({
      isShare: false,
      pubdisabled: false
    })
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      fetch(`wx/membershare/${this.data.specificarea}/addShare`, 'POST', {
        type: 1,
        typeId: 0,
        memberId: userInfo["id"]
      }).then(res => {
        this.setData({
          isShare: false,
          pubdisabled: false
        })
      })
    }
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: this.data.title, // 默认是小程序的名称(可以写slogan等)
      path: '/pages/index/index', // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl: this.data.imageList[0],
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function (com) {}
    }
    // 返回shareObj
    return shareObj;
  }
})